import fs from 'fs';

class StrokeStrFileManager{

  constructor(dir){

    this.dir = dir;
    this.upd = false;
    this.transferStr = "";

    fs.open(dir, 'a+',  (err, fd) => {
      if (err) {
        fs.chmod(dir, 0o777)
      }
      this.fd = fd;
      fs.close(this.fd, () => {

      })
    })
  }
  get(){

    return new Promise( (resolve, reject) => {

      fs.readFile(this.dir, (err, data) => {

        resolve(data.toString())
      })
    })
  }
  finishFile(){


    if(this.upd){
      return;
    }
    fs.unlink(this.dir, (err) => {

      if (err) throw err;
    })

  }

  append(str = ""){

    this.transferStr += str;
    if(this.upd){
      return
    }
    let tempStr = this.transferStr;
    this.upd = true;
    this.transferStr = "";
    fs.appendFile(this.dir, tempStr , 'utf8', (res) => {

      this.upd = false
      if (this.transferStr.length > 0 ) {
        this.append()
      }
    })

  }
}

export {StrokeStrFileManager}